<template>
  <div class="table-box">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="群组编码" prop="groupCode">
        <el-input v-model="searchForm.groupCode" placeholder="请输入群组编码" clearable />
      </el-form-item>
      <el-form-item label="群组名称" prop="groupName">
        <el-input v-model="searchForm.groupName" placeholder="请输入群组名称" clearable />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 180px">
          <el-option label="启用" value="ACTIVE" />
          <el-option label="禁用" value="INACTIVE" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <div class="header-left">
        <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增物料群组</el-button>
        <el-button type="success" @click="handleBatchEnable" :disabled="!selectedRows.length">
          批量启用
        </el-button>
        <el-button type="warning" @click="handleBatchDisable" :disabled="!selectedRows.length">
          批量禁用
        </el-button>
      </div>
      <div class="header-right">
        <el-button :icon="RefreshRight" @click="handleRefresh">刷新</el-button>
        <el-button :icon="Download" @click="handleExport">导出</el-button>
      </div>
    </div>

    <el-table 
      :data="tableData" 
      style="width: 100%" 
      v-loading="loading" 
      border
      empty-text="暂无数据"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="groupCode" label="群组编码" width="120" />
      <el-table-column prop="groupName" label="群组名称" width="150" />
      <el-table-column prop="groupTypeName" label="分组类型" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.groupTypeName" type="info" size="small">
            {{ scope.row.groupTypeName }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="sortOrder" label="排序" width="80" align="center">
        <template #default="scope">
          <el-tag type="info" size="small">{{ scope.row.sortOrder || 0 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="materialCount" label="物料数" width="90" align="center">
        <template #default="scope">
          <el-badge :value="scope.row.materialCount || 0" :max="99" type="success">
            <el-icon><Box /></el-icon>
          </el-badge>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'ACTIVE' ? 'success' : 'warning'">
            {{ scope.row.status === 'ACTIVE' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
      <el-table-column prop="createdTime" label="创建时间" width="160">
        <template #default="scope">
          <span>{{ formatDateTime(scope.row.createdTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="320" fixed="right">
        <template #default="scope">
          <el-button type="primary" link :icon="View" @click="handleView(scope.row)">详情</el-button>
          <el-button type="info" link @click="handleViewInDrawer(scope.row)">查看</el-button>
          <el-button type="primary" link :icon="EditPen" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            :type="scope.row.status === 'ACTIVE' ? 'warning' : 'success'" 
            link 
            @click="handleStatusToggle(scope.row)"
          >
            {{ scope.row.status === 'ACTIVE' ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <!-- 表单抽屉 -->
    <MaterialGroupDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="ts" name="materialGroup">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, EditPen, View, Delete, FolderOpened, Box, RefreshRight, Download } from "@element-plus/icons-vue";
import MaterialGroupDrawer from "./form.vue";
import {
  getMaterialGroupList,
  createMaterialGroup,
  updateMaterialGroup,
  deleteMaterialGroup,
  enableMaterialGroup,
  disableMaterialGroup,
  type MaterialGroup
} from "@/api/modules/materialGroup";
// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-';
  return new Date(dateTime).toLocaleString('zh-CN');
};

const loading = ref(false);
const tableData = ref<MaterialGroup.MaterialGroupListItem[]>([]);
const searchFormRef = ref<FormInstance>();
const selectedRows = ref<MaterialGroup.MaterialGroupListItem[]>([]);

// 查询表单
const searchForm = reactive({
  groupCode: "",
  groupName: "",
  status: ""
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      current: pagination.currentPage,
      size: pagination.pageSize
    };
    // 过滤空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === "" || params[key] === null || params[key] === undefined) {
        delete params[key];
      }
    });
    
    const res = await getMaterialGroupList(params);
    tableData.value = res.data.records || [];
    pagination.total = res.data.total || 0;
  } catch (error) {
    console.error("获取物料群组列表失败:", error);
    ElMessage.error("获取物料群组列表失败");
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 表单抽屉引用
const drawerRef = ref<InstanceType<typeof MaterialGroupDrawer>>();

// 新增
const handleAdd = () => {
  const params = {
    title: "新增",
    isView: false,
    row: {},
    api: addMaterialGroup,
    getTableList: getTableData
  };
  drawerRef.value?.acceptParams(params);
};

// 编辑
const handleEdit = (row: MaterialGroup.MaterialGroupListItem) => {
  const params = {
    title: "编辑",
    isView: false,
    row: { ...row },
    api: editMaterialGroup,
    getTableList: getTableData
  };
  drawerRef.value?.acceptParams(params);
};

// 新增物料群组
const addMaterialGroup = async (params: MaterialGroup.CreateMaterialGroupRequest) => {
  return await createMaterialGroup(params);
};

// 查看详情
const handleView = (row: MaterialGroup.MaterialGroupListItem) => {
  // 跳转到详情页面
  window.open(`#/basicData/material/group/detail/${row.id}`, '_blank');
};

// 在抽屉中查看
const handleViewInDrawer = (row: MaterialGroup.MaterialGroupListItem) => {
  const params = {
    title: "查看",
    isView: true,
    row: { ...row },
    api: undefined,
    getTableList: getTableData
  };
  drawerRef.value?.acceptParams(params);
};

// 编辑物料群组
const editMaterialGroup = async (params: MaterialGroup.MaterialGroupListItem) => {
  return await updateMaterialGroup(params.id, params);
};

// 删除
const handleDelete = async (row: MaterialGroup.MaterialGroupListItem) => {
  try {
    // 检查是否有关联物料
    if (row.materialCount && row.materialCount > 0) {
      ElMessage.warning("该群组下存在物料，无法删除");
      return;
    }

    await ElMessageBox.confirm(`确认删除物料群组 "${row.groupName}" 吗？`, "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      message: `<p>删除后将无法恢复，请谨慎操作！</p><p>群组编码：${row.groupCode}</p><p>群组名称：${row.groupName}</p>`
    });
    
    await deleteMaterialGroup(row.id);
    ElMessage.success("删除成功");
    getTableData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 启用/禁用状态切换
const handleStatusToggle = async (row: MaterialGroup.MaterialGroupListItem) => {
  try {
    const action = row.status === 'ACTIVE' ? '禁用' : '启用';
    await ElMessageBox.confirm(`确认${action}物料群组 "${row.groupName}" 吗？`, `${action}确认`, {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    
    if (row.status === 'ACTIVE') {
      await disableMaterialGroup(row.id);
    } else {
      await enableMaterialGroup(row.id);
    }
    
    ElMessage.success(`${action}成功`);
    getTableData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error("操作失败");
    }
  }
};

// 选择行变化
const handleSelectionChange = (selection: MaterialGroup.MaterialGroupListItem[]) => {
  selectedRows.value = selection;
};

// 刷新数据
const handleRefresh = () => {
  getTableData();
  ElMessage.success("刷新成功");
};

// 批量启用
const handleBatchEnable = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning("请选择要启用的物料群组");
    return;
  }

  try {
    await ElMessageBox.confirm(`确认启用选中的 ${selectedRows.value.length} 个物料群组吗？`, "批量启用确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const promises = selectedRows.value
      .filter(row => row.status === 'INACTIVE')
      .map(row => enableMaterialGroup(row.id));
    
    await Promise.all(promises);
    ElMessage.success("批量启用成功");
    getTableData();
    selectedRows.value = [];
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error("批量启用失败");
    }
  }
};

// 批量禁用
const handleBatchDisable = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning("请选择要禁用的物料群组");
    return;
  }

  try {
    await ElMessageBox.confirm(`确认禁用选中的 ${selectedRows.value.length} 个物料群组吗？`, "批量禁用确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const promises = selectedRows.value
      .filter(row => row.status === 'ACTIVE')
      .map(row => disableMaterialGroup(row.id));
    
    await Promise.all(promises);
    ElMessage.success("批量禁用成功");
    getTableData();
    selectedRows.value = [];
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error("批量禁用失败");
    }
  }
};

// 导出数据
const handleExport = async () => {
  try {
    ElMessage.info("正在导出数据...");
    // 这里可以调用导出API
    // await exportMaterialGroupList(searchForm);
    ElMessage.success("导出成功");
  } catch (error) {
    ElMessage.error("导出失败");
  }
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
});
</script>

<style scoped>
.search-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left,
.header-right {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}
</style>